package com.safe.app.utils.exceptions;

import com.safe.app.config.ResultBean;
import com.safe.app.utils.exceptions.base.ErrorMsgException;
import com.safe.app.utils.exceptions.base.NoAuthException;
import com.safe.app.utils.exceptions.enums.ErrorMsgEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 异常处理统一入口
 *
 * @author h2l
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler
    public ResultBean processException(HttpServletRequest request, Exception e) {
        String contextPath = request.getContextPath();
        String msg = "【========系统发生异常========】--》:" + e.getMessage() + "request url:" + contextPath;
        log.error("系统异常", msg);
        if (e instanceof NoAuthException) {
            return new ResultBean(ErrorMsgEnum.noAuthException, e.getMessage());
        } else if (e instanceof BaseException) {
            return new ResultBean(ErrorMsgEnum.badRequestException, e.getMessage());
        }else if (e instanceof ErrorMsgException){
            return new ResultBean(ErrorMsgEnum.errorServer, e.getMessage());
        }
        return new ResultBean(ErrorMsgEnum.errorServer, msg);
    }
}
